<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="站点名称" prop="siteName">
        <el-input
          v-model="queryParams.siteName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="API类型" prop="apiType">
        <el-select v-model="queryParams.apiType" placeholder="请选择API类型" style="width: 150px;" clearable>
          <el-option label="MacCMS" value="maccms" />
          <el-option label="自定义" value="custom" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px;"  clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['collect:site:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['collect:site:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collect:site:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['collect:site:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="siteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="站点ID" align="center" prop="siteId" />
      <el-table-column label="站点名称" align="center" prop="siteName" />
      <el-table-column label="采集地址" align="center" prop="siteUrl" :show-overflow-tooltip="true" />
      <el-table-column label="站点标识" align="center" prop="siteFlag" />
      <el-table-column label="API类型" align="center" prop="apiType">
        <template #default="scope">
          <dict-tag :options="dict.type.collect_api_type" :value="scope.row.apiType"/>
        </template>
      </el-table-column>
      <el-table-column label="资源类型" align="center" prop="resourceType">
        <template #default="scope">
          <dict-tag :options="dict.type.collect_resource_type" :value="scope.row.resourceType"/>
        </template>
      </el-table-column>
      <el-table-column label="自动采集" align="center" prop="autoCollect">
        <template #default="scope">
          <el-switch
            v-model="scope.row.autoCollect"
            active-value="1"
            inactive-value="0"
            @change="handleAutoCollectChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="采集次数" align="center" prop="collectCount" />
      <el-table-column label="成功数" align="center" prop="successCount" />
      <el-table-column label="最后采集时间" align="center" prop="lastCollectTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastCollectTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            icon="Connection"
            @click="handleTest(scope.row)"
            v-hasPermi="['collect:site:test']"
          >测试</el-button>
          <el-button
            size="small"
            type="primary"
            link
            icon="Link"
            @click="handleBind(scope.row)"
            v-hasPermi="['collect:bind:list']"
          >绑定</el-button>
          <el-button
            size="small"
            type="primary"
            link
            icon="Download"
            @click="handleCollect(scope.row)"
            v-hasPermi="['collect:task:add']"
          >采集</el-button>
          <el-button
            size="small"
            type="primary"
            link
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['collect:site:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="primary"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collect:site:remove']"
          >删除</el-button>
          <el-button
            size="small"
            type="danger"
            link
            icon="DeleteFilled"
            @click="handleClearData(scope.row)"
            v-hasPermi="['collect:site:remove']"
          >清空数据</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采集站点对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="siteRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="站点名称" prop="siteName">
              <el-input v-model="form.siteName" placeholder="请输入站点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点标识" prop="siteFlag">
              <el-input v-model="form.siteFlag" placeholder="请输入站点标识" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="采集地址" prop="siteUrl">
              <el-input v-model="form.siteUrl" placeholder="请输入采集API地址，如：http://example.com/api.php/provide/vod/" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="API类型" prop="apiType">
              <el-select v-model="form.apiType" placeholder="请选择API类型">
                <el-option label="MacCMS" value="maccms" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源类型" prop="resourceType">
              <el-select v-model="form.resourceType" placeholder="请选择资源类型">
                <el-option label="视频" value="1" />
                <el-option label="文章" value="2" />
                <el-option label="演员" value="8" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据格式" prop="dataFormat">
              <el-select v-model="form.dataFormat" placeholder="请选择数据格式">
                <el-option label="自动" value="0" />
                <el-option label="XML" value="1" />
                <el-option label="JSON" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字符编码" prop="charset">
              <el-select v-model="form.charset" placeholder="请选择字符编码">
                <el-option label="UTF-8" value="UTF-8" />
                <el-option label="GBK" value="GBK" />
                <el-option label="GB2312" value="GB2312" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="更新规则" prop="uprule">
              <el-select v-model="form.uprule" placeholder="请选择更新规则">
                <el-option label="追加(,a)" value=",a" />
                <el-option label="覆盖(,b)" value=",b" />
                <el-option label="合并(,c)" value=",c" />
                <el-option label="跳过(,d)" value=",d" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片处理" prop="picMode">
              <el-select v-model="form.picMode" placeholder="请选择图片处理">
                <el-option label="不处理" value="0" />
                <el-option label="同步本地" value="1" />
                <el-option label="使用代理" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="起始页码" prop="pagebase">
              <el-input-number v-model="form.pagebase" :min="1" :max="999" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="每页数量" prop="pagesize">
              <el-input-number v-model="form.pagesize" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大页数" prop="maxCollectPages">
              <el-input-number v-model="form.maxCollectPages" :min="1" :max="9999" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="自动采集" prop="autoCollect">
              <el-radio-group v-model="form.autoCollect">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采集间隔" prop="collectInterval">
              <el-input-number v-model="form.collectInterval" :min="60" :max="86400" />
              <span> 秒</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试连接对话框 -->
    <el-dialog title="测试连接" v-model="testOpen" width="600px" append-to-body>
      <pre>{{ testResult }}</pre>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="testOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 采集对话框 -->
    <el-dialog title="采集数据" v-model="collectOpen" width="500px" append-to-body>
      <el-form ref="collectFormRef" :model="collectForm" label-width="80px">
        <el-form-item label="采集方式">
          <el-radio-group v-model="collectForm.type">
            <el-radio label="all">全量采集</el-radio>
            <el-radio label="recent">最新采集</el-radio>
            <el-radio label="type">按类型</el-radio>
            <el-radio label="ids">按ID</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="小时数" v-if="collectForm.type === 'recent'">
          <el-input-number v-model="collectForm.hours" :min="1" :max="720" />
        </el-form-item>
        <el-form-item label="类型ID" v-if="collectForm.type === 'type'">
          <el-input v-model="collectForm.typeId" placeholder="请输入远程类型ID" />
        </el-form-item>
        <el-form-item label="ID列表" v-if="collectForm.type === 'ids'">
          <el-input v-model="collectForm.ids" type="textarea" placeholder="请输入ID列表,逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCollect">开始采集</el-button>
          <el-button @click="collectOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CollectSite">
import { listSite, getSite, delSite, addSite, updateSite, testSite, getCollectedDataStatistics, deleteCollectedData } from "@/api/collect/site";
import { collectAll, collectRecent, collectByType, collectByIds } from "@/api/collect/task";

const { proxy } = getCurrentInstance();
const router = proxy.$router;
const { collect_api_type, collect_resource_type } = proxy.useDict('collect_api_type', 'collect_resource_type');

const siteList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const testOpen = ref(false);
const testResult = ref("");
const collectOpen = ref(false);

const dict = reactive({
  type: {
    collect_api_type: collect_api_type,
    collect_resource_type: collect_resource_type
  }
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    siteName: null,
    apiType: null,
    status: null
  },
  collectForm: {
    siteId: null,
    type: 'all',
    hours: 24,
    siteFlag: null,
    typeId: '',
    ids: ''
  },
  rules: {
    siteName: [
      { required: true, message: "站点名称不能为空", trigger: "blur" }
    ],
    siteUrl: [
      { required: true, message: "采集地址不能为空", trigger: "blur" }
    ],
    siteFlag: [
      { required: true, message: "站点标识不能为空", trigger: "blur" }
    ],
    apiType: [
      { required: true, message: "API类型不能为空", trigger: "change" }
    ],
    resourceType: [
      { required: true, message: "资源类型不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, collectForm, rules } = toRefs(data);

/** 查询采集站点列表 */
function getList() {
  loading.value = true;
  listSite(queryParams.value).then(response => {
    siteList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    siteId: null,
    siteName: null,
    siteUrl: null,
    siteFlag: null,
    apiType: "maccms",
    apiVersion: null,
    apiConfig: null,
    charset: "UTF-8",
    collectType: null,
    resourceType: "1",
    dataFormat: "0",
    collectParam: null,
    uprule: ",c",
    filter: null,
    filterFrom: null,
    hitsStart: null,
    hitsEnd: null,
    score: null,
    picMode: "0",
    pagebase: 1,
    pagesize: 20,
    maxCollectPages: 100,
    collectInterval: 3600,
    autoCollect: "0",
    collectHours: null,
    status: "0",
    remark: null
  };
  proxy.resetForm("siteRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.siteId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加采集站点";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const siteId = row.siteId || ids.value;
  getSite(siteId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改采集站点";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["siteRef"].validate(valid => {
    if (valid) {
      if (form.value.siteId != null) {
        updateSite(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSite(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const siteIds = row.siteId || ids.value;
  proxy.$modal.confirm('是否确认删除采集站点编号为"' + siteIds + '"的数据项？').then(function() {
    return delSite(siteIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('collect/site/export', {
    ...queryParams.value
  }, `site_${new Date().getTime()}.xlsx`);
}

/** 测试连接 */
function handleTest(row) {
  testResult.value = "正在测试连接...";
  testOpen.value = true;
  testSite(row.siteId).then(response => {
    testResult.value = response.msg || response.data;
  }).catch(error => {
    testResult.value = "测试失败: " + error;
  });
}

/** 管理绑定 */
function handleBind(row) {
  router.push("/collect/bind?siteId=" + row.siteId);
}

/** 采集数据 */
function handleCollect(row) {
  collectForm.value.siteId = row.siteId;
  collectForm.value.siteFlag = row.siteFlag;
  collectOpen.value = true;
}

/** 提交采集 */
function submitCollect() {
  const siteId = collectForm.value.siteId;
  let promise;

  switch(collectForm.value.type) {
    case 'all':
      promise = collectAll(siteId);
      break;
    case 'recent':
      promise = collectRecent(siteId, collectForm.value.hours);
      break;
    case 'type':
      promise = collectByType(siteId, collectForm.value.typeId);
      break;
    case 'ids':
      promise = collectByIds(siteId, collectForm.value.ids);
      break;
  }

  promise.then(response => {
    proxy.$modal.msgSuccess("采集任务已创建");
    collectOpen.value = false;
    // 跳转到任务列表
    router.push("/collect/task");
  });
}

/** 自动采集状态修改 */
function handleAutoCollectChange(row) {
  let text = row.autoCollect === "1" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.siteName + '"的自动采集吗？').then(function() {
    return updateSite(row);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function() {
    row.autoCollect = row.autoCollect === "0" ? "1" : "0";
  });
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.siteName + '"吗？').then(function() {
    return updateSite(row);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function() {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 清空采集数据 */
function handleClearData(row) {
  // 1. 先获取统计信息
  getCollectedDataStatistics(row.siteId).then(response => {
    const stat = response.data;
    const message = `确认删除站点【${row.siteName}】的所有采集数据？\n\n将删除:\n  - 影视: ${stat.movieCount || 0} 部\n  - 播放资源: ${stat.resourceCount || 0} 条\n  - 演职人员: ${stat.castCount || 0} 条\n\n此操作不可恢复！`;

    // 2. 二次确认
    proxy.$modal.confirm(message, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 3. 显示加载提示
      const loadingInstance = proxy.$loading({
        lock: true,
        text: '正在删除数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 4. 执行删除
      deleteCollectedData(row.siteId).then(response => {
        loadingInstance.close();
        proxy.$modal.msgSuccess("删除成功");
        getList();  // 刷新列表
      }).catch(() => {
        loadingInstance.close();
      });
    });
  }).catch(error => {
    proxy.$modal.msgError("获取数据统计失败，请重试");
  });
}

getList();
</script>
